# -*- coding: utf-8 -*-

import filecmp
import os
import sys
import openpyxl
import pymysql

STT_ERROR_TEXT = 1

def tryreplacefile(filename):
    if not os.path.exists(filename[:-1]) or \
        not filecmp.cmp(filename, filename[:-1], False):
        os.replace(filename, filename[:-1])
    else:
        os.remove(filename)

def importxlsx2db(conn, xlsfile, cxxfile):
    wb = openpyxl.load_workbook(xlsfile, read_only=True, data_only=True)
    ws = wb.active
    cxxfo = open(cxxfile, 'w')
    cursor = conn.cursor()

    cxxfo.write('#pragma once\n\n')
    cxxfo.write('enum GErrorCode\n{\n')
    cursor.execute('DELETE FROM string_text_list WHERE (stringID>>24)=%s', STT_ERROR_TEXT)
    enumValue = 0
    for row in range(ws.max_row):
        enumName = ws.cell(row + 1, 1).value
        enumName = enumName and enumName.strip() or None
        if enumName:
            cxxfo.write('\t%s,\n' % enumName)
            cursor.execute('INSERT INTO string_text_list(stringID,stringCN) VALUES(%s,%s)',
                ((STT_ERROR_TEXT << 24) + enumValue, ws.cell(row + 1, 2).value))
            enumValue += 1
        else:
            cxxfo.write('\n')
    cxxfo.write('};\n')

    conn.commit()
    cursor.close()
    cxxfo.close()

    tryreplacefile(cxxfile)

if __name__ == '__main__':
    conn = pymysql.connect(host='127.0.0.1', user='app', password='123456',
        database='mmorpg_world', port=3306, charset='utf8mb4')
    try:
        importxlsx2db(conn, sys.argv[1], sys.argv[2])
    finally:
        conn.close()
